package com.cyt.web.controller.work.question;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cyt.base.enums.BusinessType;
import com.cyt.base.enums.OperatorType;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.ErrorCode;
import com.cyt.base.util.StringUtils;
import com.cyt.sys.aspect.BaseLog;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.web.controller.base.BaseController;
import com.cyt.work.question.model.po.Question;
import com.cyt.work.question.model.po.QuestionUser;
import com.cyt.work.question.model.vo.QuestionUserImportVo;
import com.cyt.work.question.model.vo.QuestionVo;
import com.cyt.work.question.service.IQuestionService;
import com.cyt.work.question.service.IQuestionUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 问卷管理表 前端控制器
 *
 * @author concong tao
 * @since 2019-01-31
 */
@RestController
public class QuestionController extends BaseController {

    @Autowired
    private IQuestionUserService questionUserService;
    @Autowired
    private IQuestionService questionService;

    /**
     * 统一跳转
     *
     * @param pageName 页面名称
     * @param applyId 应用id
     * @return ModelAndView
     * @author shengQiang Yu
     * @date 2019-08-28 15:17:40
     */
    @RequestMapping("/work/question/{pageName}")
    public ModelAndView goPage(@PathVariable("pageName") String pageName, String applyId) {
        ModelAndView view = new ModelAndView("/work/question/"+pageName);
        view.addObject("applyId", applyId);
        return view;
    }

    /**
     * 问卷分页查询
     * @param questionVo 查询参数
     * @param page        当前页面
     * @param limit       页面数量
     * @author congcong tao
     * @date 2019/7/10 14:59
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "分页查询对象", businessType = BusinessType.GET, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/page", method = RequestMethod.POST)
    public ReturnResult page(QuestionVo questionVo, int page, int limit) {
        return questionService.pageManage(questionVo, limit, page);
    }

    /**
     * 根据ID查询问卷详情
     * @param id
     * @author congcong tao
     * @date 2019/7/10 15:00
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "根据ID查询问卷详情", businessType = BusinessType.GET, operatorType = OperatorType.MANAGE)
    @RequestMapping("/work/question/getInfo")
    public ReturnResult info(String id){
        Question question = questionService.getInfo(id, "");
        return new ReturnResult(question);
    }

    /**
     * 跳转添加或编辑界面
     * @param id 主键
     * @author congcong tao
     * @date 2019/7/10 15:03
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "跳转添加或编辑界面", businessType = BusinessType.GET, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/getEdit", method = RequestMethod.GET)
    public ModelAndView getEdit(String id, String parentMenuId, String applyId) {
        ModelAndView view = new ModelAndView("/work/question/questionEdit");
        if (StrUtil.isNotEmpty(id)) {
            Question question = questionService.getInfo(id, "");
            view.addObject("question", question);
        }
        view.addObject("applyId", applyId);
        view.addObject("parentMenuId", parentMenuId);
        return view;
    }

    /**
     * 问卷查看页面
     * @param id
     * @param parentMenuId
     * @author congcong tao
     * @date 2019/8/21 15:15
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "统计页面", businessType = BusinessType.GET, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/getShow", method = RequestMethod.GET)
    public ModelAndView getShow(String id, String parentMenuId) {
        ModelAndView view = new ModelAndView("/work/question/questionShow");
        if (StrUtil.isNotEmpty(id)) {
            Question question = questionService.getInfo(id, null);
            view.addObject("question", question);
        }
        view.addObject("parentMenuId", parentMenuId);
        return view;
    }

    /**
     * 监管页面
     * @param id
     * @param parentMenuId
     * @author congcong tao
     * @date 2019/9/2 11:54
     */
    @RequestMapping(value = "/work/question/getSupervise", method = RequestMethod.GET)
    public ModelAndView getSupervise(String id, String parentMenuId) {
        ModelAndView view = new ModelAndView("/work/question/questionSupervise");
        if (StrUtil.isNotEmpty(id)) {
            Question question = questionService.selectByPrimaryKey(id);
            view.addObject("question", question);
        }
        view.addObject("parentMenuId", parentMenuId);
        return view;
    }

    /**
     * 统计页面
     * @param id
     * @param parentMenuId
     * @author congcong tao
     * @date 2019/9/2 11:54
     */
    @RequestMapping(value = "/work/question/getTotal", method = RequestMethod.GET)
    public ModelAndView getTotal(String id, String parentMenuId) {
        ModelAndView view = new ModelAndView("/work/question/questionTotal");
        if (StrUtil.isNotEmpty(id)) {
            Question question = questionService.getTotalInfo(id);
            view.addObject("question", question);
        }
        view.addObject("parentMenuId", parentMenuId);
        return view;
    }

    /**
     * 问卷复制
     * @param id
     * @author congcong tao
     * @date 2019/9/4 9:39
     */
    @RequestMapping(value = "/work/question/getQuestionCopy", method = RequestMethod.GET)
    public ModelAndView getQuestionCopy(String id) {
        ModelAndView view = new ModelAndView("/work/question/questionCopy");
        if (StrUtil.isNotEmpty(id)) {
            Question question = questionService.selectByPrimaryKey(id);
            view.addObject("question", question);
        }
        return view;
    }

    /**
     * 发布页面
     * @param id
     * @param parentMenuId
     * @author congcong tao
     * @date 2019/9/2 11:54
     */
    @RequestMapping(value = "/work/question/getPublish", method = RequestMethod.GET)
    public ModelAndView getPublish(String id, String parentMenuId) {
        ModelAndView view = new ModelAndView("/work/question/questionPublish");
        if (StrUtil.isNotEmpty(id)) {
            Question question = questionService.getInfo(id, "");
            view.addObject("question", question);
        }
        view.addObject("parentMenuId", parentMenuId);
        return view;
    }

    /**
     * 问卷简答题详情
     * @param id 问卷主键
     * @param subjectId 题目主键
     * @param parentMenuId
     * @author congcong tao
     * @date 2019/9/4 9:00
     */
    @RequestMapping(value = "/work/question/getQuestionSubject", method = RequestMethod.GET)
    public ModelAndView getQuestionSubject(String id, String subjectId) {
        ModelAndView view = new ModelAndView("/work/question/questionSubjectDetail");
        if (StrUtil.isNotEmpty(id)) {
            Question question = questionService.selectByPrimaryKey(id);
            view.addObject("question", question);
        }
        view.addObject("subjectId", subjectId);
        return view;
    }

    /**
     * 保存问卷
     * @param request
     * @param question
     * @author congcong tao
     * @date 2019/7/10 15:04
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "保存对象", businessType = BusinessType.INSERT, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/save", method = RequestMethod.POST)
    public ReturnResult save(HttpServletRequest request, String questionJson){
        Question question = JSONObject.parseObject(questionJson, Question.class);
        if (StringUtils.isEmpty(question.getStartTimeStr())) {
            return new ReturnResult(ErrorCode.CODE_1, "请填写开始时间");
        }
        question.setStartTime(DateUtil.parseDate(question.getStartTimeStr()));
        if (StringUtils.isEmpty(question.getEndTimeStr())) {
            return new ReturnResult(ErrorCode.CODE_1, "请填写结束时间");
        }
        question.setEndTime(DateUtil.parseDate(question.getEndTimeStr()));
        // 开始时间和结束时间的判断
        ReturnResult returnResult = questionService.checkTime(question.getStartTime(), question.getEndTime());
        if (returnResult.getCode() != 0) {
            return returnResult;
        }
        return questionService.saveQuestion(request, question, acceptCurrentUser(request));
    }

    /**
     * 更新问卷
     * @param questionJson
     * @author congcong tao
     * @date 2019/7/10 15:04
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "更新对象", businessType = BusinessType.UPDATE, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/update", method = RequestMethod.POST)
    public ReturnResult update(HttpServletRequest request, String questionJson){
        Question question = JSONObject.parseObject(questionJson, Question.class);
        if (StringUtils.isEmpty(question.getStartTimeStr())) {
            return new ReturnResult(ErrorCode.CODE_1, "请填写开始时间");
        }
        question.setStartTime(DateUtil.parseDate(question.getStartTimeStr()));
        if (StringUtils.isEmpty(question.getEndTimeStr())) {
            return new ReturnResult(ErrorCode.CODE_1, "请填写结束时间");
        }
        question.setEndTime(DateUtil.parseDate(question.getEndTimeStr()));
        // 开始时间和结束时间的判断
        ReturnResult returnResult = questionService.checkTime(question.getStartTime(), question.getEndTime());
        if (returnResult.getCode() != 0) {
            return returnResult;
        }
        return questionService.updateQuestion(request, question, acceptCurrentUser(request));
    }

    /**
     * 复制问卷
     * @param request
     * @param questionVo
     * @author congcong tao
     * @date 2019/9/4 9:42
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "复制问卷", businessType = BusinessType.INSERT, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/copy", method = RequestMethod.POST)
    public ReturnResult save(HttpServletRequest request, QuestionVo questionVo){
        return questionService.copyQuestion(request, questionVo);
    }

    /**
     * 删除问卷
     * @param id
     * @author congcong tao
     * @date 2019/7/10 15:04
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "删除对象", businessType = BusinessType.DELETE, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/deleteQuestion")
    public ReturnResult deleteQuestion(String id){
        int flag = questionService.deleteQuestion(id);
        if (flag <= 0) {
            return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_ADD_FAIL_MSG);
        }
        return new ReturnResult();
    }

    /**
     * 发布问卷
     * @param id
     * @author congcong tao
     * @date 2019/7/10 15:10
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "发布问卷", businessType = BusinessType.UPDATE, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/updateStatus")
    public ReturnResult updateStatus(HttpServletRequest request, String id, String status){
        return questionService.updateStatus(id, status, acceptCurrentUser(request));
    }

    /**
     * 结束问卷
     * @param id
     * @param status
     * @author congcong tao
     * @date 2019/9/10 15:16
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "结束问卷", businessType = BusinessType.UPDATE, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/finish")
    public ReturnResult finish(String id, String status){
        Question question = questionService.selectByPrimaryKey(id);
        question.setId(id);
        question.setStatus(status);
        int flag = questionService.updateByPrimaryKeySelective(question);
        if (flag <= 0) {
            return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_ADD_FAIL_MSG);
        }
        return new ReturnResult();
    }

    /**
     * 发布中更新人员信息
     * @param id 问卷主键
     * @param userJson
     * @author congcong tao
     * @date 2019/9/9 9:48
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "更新人员", businessType = BusinessType.UPDATE, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/updateQuestionUser")
    public ReturnResult updateQuestionUser(String id, String userJson){
        // 只增加人，需要校验人是否已在发布中
        List<QuestionUser> userList = JSONArray.parseArray(userJson, QuestionUser.class);
        if (userList != null && userList.size() > 0) {
            List<QuestionUser> questionUserList = new ArrayList<>();
            for (QuestionUser questionUser : userList) {
                // 查询是否在发布中
                QuestionUser questionUserSearch = new QuestionUser();
                questionUserSearch.setQuestionId(id);
                questionUserSearch.setUserId(questionUser.getUserId());
                List<QuestionUser> list = questionUserService.select(questionUserSearch);
                if (list != null && list.size() > 0) {
                    continue;
                }
                questionUser.setId(BaseUtil.uId());
                questionUser.setQuestionId(id);
                questionUser.setCreateTime(DateUtil.date());
                questionUserList.add(questionUser);
            }
            if (questionUserList != null && questionUserList.size() > 0) {
                questionUserService.insertList(questionUserList);
            }
        }
        return new ReturnResult();
    }

    /**
     * 问卷按月统计
     *
     * @param questionVo 参数传入对象
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-08-21 14:18
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "问卷按月统计", businessType = BusinessType.GET, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/statisticsByMonth", method = RequestMethod.POST)
    public ReturnResult statisticsByMonth(QuestionVo questionVo) {
        return questionService.statisticsByMonth(questionVo);
    }

    /**
     * 统计已答卷人员
     * @param questionVo
     * @author congcong tao
     * @date 2019/9/2 16:10
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "统计已答卷人员", businessType = BusinessType.GET, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/statisticsUser", method = RequestMethod.POST)
    public ReturnResult statisticsUser(QuestionVo questionVo, int page, int limit) {
        return questionService.pageStatisticsUser(questionVo, limit, page);
    }

    /**
     * 导入问卷用户，主要需要保存到学校用户表
     * @param file
     * @param request
     * @author congcong tao
     * @date 2019/9/3 13:33
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "导入问卷用户", businessType = BusinessType.IMPORT, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/importExcel", method = RequestMethod.POST)
    public ReturnResult importExcel(MultipartFile file, HttpServletRequest request, String applyId) {
        return questionService.importExcel(file, applyId, acceptCurrentUser(request));
    }

    /**
     * 导出问卷用户模板
     * @param response
     * @author congcong tao
     * @date 2019/9/3 13:43
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "导出问卷用户模板", businessType = BusinessType.EXPORT, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        List<QuestionUserImportVo> list = new ArrayList<>();
        list.add(new QuestionUserImportVo("C20150101", "张三", "2", "13366388088"));
        list.add(new QuestionUserImportVo("C20150102", "李四", "3", "13366388088"));
        // 导出操作
        EasyPoiUtil.exportExcel(list, "用户信息", "用户信息", QuestionUserImportVo.class, "用户信息.xls", response);
    }

    /**
     * 导出问卷相关用户数据
     * @param response
     * @author congcong tao
     * @date 2019/9/9 9:34
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "导出问卷相关用户数据", businessType = BusinessType.EXPORT, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/exportUserExcel")
    public void exportUserExcel(HttpServletResponse response, String questionId) {
        List<QuestionUserImportVo> list = questionUserService.selectExportUserByQuestionId(questionId);
        // 导出操作
        EasyPoiUtil.exportExcel(list, "用户信息", "用户信息", QuestionUserImportVo.class, "用户信息.xls", response);
    }

    @BaseLog(module = "问卷", classz = "问卷", methods = "导出统计结果", businessType = BusinessType.EXPORT, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/exportTotalExcel")
    public void exportTotalExcel(HttpServletResponse response, String questionId) {
        questionService.exportTotalExcel(response, questionId);
    }

    /**
     * 导出个人问卷详情
     */
    @BaseLog(module = "问卷", classz = "问卷", methods = "导出明细详情", businessType = BusinessType.EXPORT, operatorType = OperatorType.MANAGE)
    @RequestMapping(value = "/work/question/exportUserScoreExcel")
    public void exportUserScoreExcel(HttpServletResponse response, String questionId) {
        questionService.exportUserScoreExcel(response, questionId);
    }
}